package juc.aqs;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
* CyclicBarrier 优化 可实现线程完成计数的重用
* */
public class Test8 {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2,()->{

            System.out.println("任务汇总...task1 task 2");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        for (int i = 0; i <3 ; i++) {
            threadPool.submit(()->{
                System.out.println("task1 ing");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("task1 ed");
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
           threadPool.submit(()->{
               System.out.println("task2 ing");
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               System.out.println("task2 ed");
               try {
                   barrier.await();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               } catch (BrokenBarrierException e) {
                   e.printStackTrace();
               }
           });
        }
        threadPool.shutdown();
    }
}
